import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user/user'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from '@/apis/cart/cart'
export const useUserInfoStore = defineStore('user', () => {

    const cartStore =  useCartStore()

    const userInfo = ref({})

    const getUserInfo = async ({account,password}) => {
        const res = await loginAPI({account,password})
        userInfo.value = res.result
        //合并购物车
        const localCart = ref([])
        cartStore.cartList.forEach((item)=>{
          const {skuId,selected,count} = item
          localCart.value.push({skuId,selected,count})
        })
        await mergeCartAPI(localCart.value)
        await cartStore.updateCartList()
    }
     // 退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = ref({})
    cartStore.clearCart()
  }
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }

},
{
  persist: true,
},)
